<template>
    <view class="section">
      <view :style="{ height: navBarHeight + 'px', background: '#fff' }">
        <image
          src="/static/left.png"
          mode="scaleToFill"
          class="icon"
          @click="goback"
        />
      </view>
      <view v-if="loading" class="loading-form">
        <loading-modal />
      </view>
      <view v-else>
        <view class="container">
          <view class="container-inner">
            <!-- 标题 -->
            <view class="title-section fade-in">
              <text class="title">台球杆估值结果</text>
              <text class="subtitle">基于市场数据分析的专业估值</text>
            </view>

            <!-- 估值卡片组件 -->
            <ValuationCard :priceRange="priceRange" />

            <!-- 市场行情图表组件 -->
            <MarketChart :chartData="chartData" />

            <!-- 建议卡片 -->
            <AdviceCard :profAdvice="profAdvice" :suppExp="suppExp" />
          </view>
        </view>
      </view>
    </view>
  </template>
  
  <script setup>
  import { ref, computed } from 'vue'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { request } from '../utils/request'
  
  const loading = ref(true)
  const markdown = ref('')
  const querId = ref('')
  const navBarHeight = ref(0)
  const priceRange = computed(() => {
    const data = markdown.value.match(/"estValue":\s*\[(.*?)\]/)
    const values = data ? data[1].split(',').map(Number) : []
    return values.length === 2 ? `${values[0]}～${values[1]}` : ''
  })
  const profAdvice = computed(() => {
    const data = markdown.value.match(/"profAdvice":\s*"([^"]+)"/)
    return data ? data[1] : ''
  })
  const suppExp = computed(() => {
    const data = markdown.value.match(/"suppExp":\s*"([^"]+)"/)
    return data ? data[1] : ''
  })
  let socket = null
  const chartData = ref({
    categories: ['3月前', '2月前', '1月前'],
    series: [
    {
      name: '价格',
      data: computed(() => {
        const data = markdown.value.match(/"marketTrend":\s*\[(.*?)\]/)
        return data ? data[1].split(',').map(Number) : []
      })
    }
  ]
  });
  const getNavHeight = () => {
		const systemInfo = uni.getSystemInfoSync()
		const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		// 状态栏高度
		const statusBarHeight = systemInfo.statusBarHeight || 20
		// 胶囊按钮高度
		const capsuleHeight = menuButtonInfo.height || 32
		// 胶囊与状态栏的间距
		const topGap = menuButtonInfo.top - statusBarHeight
		// 整个自定义导航栏高度
		navBarHeight.value = (statusBarHeight + capsuleHeight + topGap * 2)
	}
  const getData = (id) => {
    socket = uni.connectSocket({
      url: `ws://106.53.100.223:8878/ws`,
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('WebSocket连接成功', res)
      }
    })
    socket.onOpen((res) => {
      console.log('WebSocket连接已打开', res, querId.value)
      socket.send({
        data: `auth:${id}`,
        success() {
          console.log('✅ 已发送认证信息')
          request({
            url: `/user/assess/generate/${querId.value}`,
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
              id: querId.value
            }
          })
        },
        fail(err) {
          console.error('❌ 发送失败:', err)
        }
      })
    })
    // 接收服务器消息
    socket.onMessage((res) => {
      console.log('📩 收到消息:', res.data)
      loading.value = false;
      markdown.value = JSON.parse(res.data);
    })
    // 错误处理
    socket.onError((err) => {
      console.error('❌ WebSocket 错误:', err)
    })

    // 连接关闭时
    socket.onClose(() => {
      console.log('🔌 WebSocket 已关闭')
    })
    
  }
  const goback = () => {
    uni.redirectTo({url: '/pages/index/project'})
  }
  onLoad((options) => {
    getNavHeight()
    const id = decodeURIComponent(options.id)
    querId.value = id
    const userInfo = uni.getStorageSync('userInfo')
    getData(userInfo.id)
  })

  onUnload(() => {
    if (socket) {
      socket.close()
    }
  })

</script>
<style scoped>
.container {
  font-family: 'sans-serif';
  background-color: #F5F7FA;
}
.icon{
  width: 40rpx;
  height: 40rpx;
  margin: 20rpx;
  position: absolute;
  top: 60rpx;
}
.text-primary {
  color: #005FE3;
}
.text-text-light {
  color: #666;
}
.fade-in {
  animation: fadeIn 0.6s ease-out forwards;
}
@keyframes fadeIn {
  from { opacity: 0 }
  to { opacity: 1 }
}
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.container-inner {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 48rpx 32rpx;
}
.title-section {
  text-align: center;
  margin-bottom: 48rpx;
  animation: fade-in 0.6s ease-in-out;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #275ddb;
  display: block;
}

.subtitle {
  display: block;
  margin-top: 16rpx;
  color: #999999;
  font-size: 28rpx;
}
/* 小程序支持的 fade-in 动画 */
@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(16rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>